package poi;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用一句话描述该文件作用
 *
 * @Author pengsamkee
 * create at 2016/11/10 11:33
 */
public class ExcelReader {

    private static final Logger logger = LoggerFactory.getLogger(ExcelReader.class);

    private File file;
    private Workbook workBook;
    private Sheet sheet;
    private List<String> columnHeaderList;
    public Map<String, String> clientColumnHeaderMap;
    public Map<String, String> serverColumnHeaderMap;
    private List<List<String>> listData;
    public List<List<List<String>>> listDatas;
    private List<Map<String, String>> serverMapData;
    public List<Map<String, String>> serverMapDatas;
    private List<Map<String, String>> clientMapData;
    public List<Map<String, String>> clientMapDatas;
    public List<List<String>> columnData;
    public String fileName;
    public String packagePath = "";
    public String packageName = "";

    public ExcelReader(File file, String excelDirectoryPath) {
        this.file = file;
        this.fileName = FilenameUtils.removeExtension(file.getName());
        this.packageName = file.getParent().substring(excelDirectoryPath.length());
        if (this.packageName != null && !this.packageName.equals("")) {
            this.packagePath = this.packageName = this.packageName.substring(1);
            this.packageName = this.packageName.replace(File.separator, ".");
        }
        this.listDatas = new ArrayList<>();
        this.serverMapDatas = new ArrayList<>();
        this.clientMapDatas = new ArrayList<>();
        this.columnData = new ArrayList<>();
        this.columnHeaderList = new ArrayList<>();
        this.clientColumnHeaderMap = new HashMap<>();
        this.serverColumnHeaderMap = new HashMap<>();
        this.load();
    }

    private void load() {
        FileInputStream inStream = null;
        try {

            inStream = new FileInputStream(this.file);
            workBook = WorkbookFactory.create(inStream);
            for (int index = 0; index < workBook.getNumberOfSheets(); index++) {
                sheet = workBook.getSheetAt(index);
                getSheetData();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private void getSheetData() {
        listData = new ArrayList<>();
        serverMapData = new ArrayList<>();
        clientMapData = new ArrayList<>();
        List<String> tempColumnHeaderList = new ArrayList<>();
        int numOfRows = sheet.getLastRowNum() + 1;
        int lastCellNum;
        for (int i = 0; i < numOfRows; i++) {
            Row row = sheet.getRow(i);
            Map<String, String> serverMap = new HashMap<>();
            Map<String, String> clientMap = new HashMap<>();
            List<String> columns = new ArrayList<>();
            List<String> list = new ArrayList<>();
            if (row != null) {
                lastCellNum = row.getLastCellNum();
                for (int j = 0; j < lastCellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (0 == i) {
                        if (0 == j) {
                            if (!getCellValue(cell).toLowerCase().equals("yes")) {
                                //不需要读取此表
                                i = numOfRows;
//                                j = lastCellNum;
                                break;
                            }
                        } else {
                            if (columnHeaderList.size() > 0 && !getCellValue(cell).equals(columnHeaderList.get(j - 1))) {
                                logger.error(String.format("=========%s 的Sheet字段格式不统一=========", this.file.getPath()));
                                i = numOfRows;
                                j = lastCellNum;
                            }
                            tempColumnHeaderList.add(getCellValue(cell));
                        }
                    } else if (1 == i) {
                        if (0 == j) {
                            if (getCellValue(cell).toLowerCase().equals("no")) {
//                                j = lastCellNum;
                            }
                        } else {
                            if (!getCellValue(cell).toLowerCase().equals("no"))
                                clientColumnHeaderMap.put(tempColumnHeaderList.get(j - 1), this.getCellValue(cell));
                        }
                    } else if (2 == i) {
                        if (0 == j) {
                            if (getCellValue(cell).toLowerCase().equals("no")) {
//                                j = lastCellNum;
                            }
                        } else {
                            if (!getCellValue(cell).toLowerCase().equals("no"))
                                serverColumnHeaderMap.put(tempColumnHeaderList.get(j - 1), this.getCellValue(cell));
                        }
                    } else {
                        if (j > 0 && !getCellValue(row.getCell(0)).toLowerCase().equals("no")){
                            if (!getCellValue(sheet.getRow(1).getCell(0)).toLowerCase().equals("no") && clientColumnHeaderMap.containsKey(tempColumnHeaderList.get(j - 1))) {
                                clientMap.put(tempColumnHeaderList.get(j - 1), this.getCellValue(cell));
                            }
                            if (!getCellValue(sheet.getRow(2).getCell(0)).toLowerCase().equals("no") && serverColumnHeaderMap.containsKey(tempColumnHeaderList.get(j - 1))) {
                                serverMap.put(tempColumnHeaderList.get(j - 1), this.getCellValue(cell));
                            }
                        }
                        columns.add(this.getCellValue(cell));
                    }
                    list.add(this.getCellValue(cell));
                }
            }
            if (i > 0 && serverMap.size() > 0) {
                serverMapData.add(serverMap);
            }
            if (i > 0 && clientMap.size() > 0) {
                clientMapData.add(clientMap);
            }
            if (i > 0 && columns.size() > 0) {
                columnData.add(columns);
            }
            if (i > 0 && tempColumnHeaderList.size() > 0 && columnHeaderList.size() == 0) {
                columnHeaderList.addAll(tempColumnHeaderList);
            }
            if (list.size() > 0)
                listData.add(list);
        }
        if (serverMapData.size() > 0)
            serverMapDatas.addAll(serverMapData);
        if (clientMapData.size() > 0)
            clientMapDatas.addAll(clientMapData);
        if (listData.size() > 0)
            this.listDatas.add(listData);
    }

    private String getCellValue(Cell cell) {
        String cellValue = "";
        DataFormatter formatter = new DataFormatter();
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = formatter.formatCellValue(cell);
                    } else {
                        double value = cell.getNumericCellValue();
                        int intValue = (int) value;
                        cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    cellValue = String.valueOf(cell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    cellValue = "";
                    break;
                case Cell.CELL_TYPE_ERROR:
                    cellValue = "";
                    break;
                default:
                    cellValue = cell.toString().trim();
                    break;
            }
        }
        return cellValue.trim();
    }

}
